import { Prisma } from '@prisma/client';
import { GetLocalTime } from '../utils/util';
import { isArray } from 'class-validator';

function transformDate(row: any) {
  if (row && row['createdAt']) {
    row.createdAt = GetLocalTime(row.createdAt as string);
  }
  if (row && row['updatedAt']) {
    row.updatedAt = GetLocalTime(row.updatedAt as string);
  }
}

export function UsePrismaAutoDateMiddleware(): Prisma.Middleware {
  return async (params, next) => {
    const result = await next(params);
    if (isArray(result)) {
      (result || []).forEach((row: any) => {
        transformDate(row);
      });
    } else {
      transformDate(result);
    }
    return result;
  };
}
